package api

import (
	"encoding/json"
	"strconv"
	"supershare/backend/models"
	"supershare/backend/utils"
	"time"

	"github.com/beego/beego/v2/core/logs"
	"github.com/beego/beego/v2/server/web"
)

// MeituanController 美团API控制器
type MeituanController struct {
	web.Controller
}

// ReceiveCallback 接收美团回调
func (c *MeituanController) ReceiveCallback() {
	// 解析请求参数
	var req struct {
		Type    string                 `json:"type"`     // 回调类型
		OrderId string                 `json:"order_id"` // 订单ID
		Data    map[string]interface{} `json:"data"`     // 回调数据
		Sign    string                 `json:"sign"`     // 签名
	}
	err := json.Unmarshal(c.Ctx.Input.RequestBody, &req)
	if err != nil {
		logs.Error("解析美团回调请求参数失败: %v", err)
		c.Data["json"] = map[string]interface{}{
			"code": 1,
			"msg":  "无效的请求参数",
		}
		c.ServeJSON()
		return
	}

	// 处理不同类型的回调
	switch req.Type {
	case "order_create":
		// 处理订单创建回调
		handleOrderCreate(req.OrderId, req.Data)
	case "order_status_update":
		// 处理订单状态更新回调
		handleOrderStatusUpdate(req.OrderId, req.Data)
	default:
		logs.Error("未知的回调类型: %s", req.Type)
	}

	// 返回成功响应
	c.Data["json"] = map[string]interface{}{
		"code": 0,
		"msg":  "success",
	}
	c.ServeJSON()
}

// SyncOrders 手动同步美团订单
func (c *MeituanController) SyncOrders() {
	// 获取门店ID参数
	storeIdStr := c.GetString("store_id")
	if storeIdStr == "" {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "门店ID不能为空",
		}
		c.ServeJSON()
		return
	}

	// 转换门店ID为整数
	storeId, err := strconv.ParseInt(storeIdStr, 10, 64)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无效的门店ID",
		}
		c.ServeJSON()
		return
	}

	// 获取门店的美团配置
	config, err := models.GetMeituanByStoreId(storeId)
	if err != nil {
		logs.Error("获取门店美团配置失败: %v", err)
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "获取门店美团配置失败",
		}
		c.ServeJSON()
		return
	}

	if config == nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "该门店未配置美团信息",
		}
		c.ServeJSON()
		return
	}

	// 检查配置状态
	if config.Status != 1 {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "美团配置已禁用，无法同步",
		}
		c.ServeJSON()
		return
	}

	// 获取时间范围参数
	startTimeStr := c.GetString("start_time", "")
	endTimeStr := c.GetString("end_time", "")

	startTime := time.Now().Add(-24 * time.Hour) // 默认同步最近24小时
	endTime := time.Now()

	if startTimeStr != "" {
		parsedTime, err := time.ParseInLocation("2006-01-02 15:04:05", startTimeStr, time.Local)
		if err == nil {
			startTime = parsedTime
		}
	}

	if endTimeStr != "" {
		parsedTime, err := time.ParseInLocation("2006-01-02 15:04:05", endTimeStr, time.Local)
		if err == nil {
			endTime = parsedTime
		}
	}

	// 创建美团API客户端
	meituanAPI := utils.NewMeituanAPI(config.AppKey, config.AppSecret, config.PoiId)

	// 获取美团订单
	orders, err := meituanAPI.GetOrders(startTime, endTime)
	if err != nil {
		logs.Error("获取美团订单失败: %v", err)
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "获取美团订单失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 处理订单
	count := 0
	for _, orderData := range orders {
		// 提取订单ID
		orderId, ok := orderData["order_id"].(string)
		if !ok || orderId == "" {
			continue
		}

		// 检查订单是否已存在
		existingOrder, _ := models.GetMeituanOrderByOrderId(orderId)
		if existingOrder != nil {
			continue
		}

		// 提取订单数据并保存
		saveOrder(config, orderData)
		count++
	}

	// 更新最后同步时间
	config.LastSyncTime = endTime.Unix()
	err = models.UpdateMeituan(config)
	if err != nil {
		logs.Error("更新最后同步时间失败: %v", err)
	}

	// 返回结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "同步完成",
		"data": map[string]interface{}{
			"total":      len(orders),
			"new_orders": count,
			"start_time": startTime.Format("2006-01-02 15:04:05"),
			"end_time":   endTime.Format("2006-01-02 15:04:05"),
			"last_sync":  endTime.Format("2006-01-02 15:04:05"),
		},
	}
	c.ServeJSON()
}

// 处理订单创建回调
func handleOrderCreate(orderId string, data map[string]interface{}) {
	logs.Info("收到美团订单创建回调, 订单ID: %s", orderId)

	// 检查订单是否已存在
	existingOrder, err := models.GetMeituanOrderByOrderId(orderId)
	if err != nil {
		logs.Error("检查订单是否存在失败: %v", err)
		return
	}

	if existingOrder != nil {
		logs.Info("订单 %s 已存在，跳过", orderId)
		return
	}

	// 从数据中提取门店ID
	poiId, ok := data["poi_id"].(string)
	if !ok || poiId == "" {
		logs.Error("无法从回调数据中获取门店ID")
		return
	}

	// 根据PoiId查找美团配置
	o := models.GetOrm()
	var config models.Meituan
	err = o.QueryTable(new(models.Meituan)).
		Filter("poi_id", poiId).
		Filter("is_deleted", 0).
		One(&config)

	if err != nil {
		logs.Error("根据PoiID查找美团配置失败: %v", err)
		return
	}

	// 保存订单
	saveOrder(&config, data)
}

// 处理订单状态更新回调
func handleOrderStatusUpdate(orderId string, data map[string]interface{}) {
	logs.Info("收到美团订单状态更新回调, 订单ID: %s", orderId)

	// 获取订单
	order, err := models.GetMeituanOrderByOrderId(orderId)
	if err != nil {
		logs.Error("获取美团订单失败: %v", err)
		return
	}

	if order == nil {
		logs.Error("订单 %s 不存在", orderId)
		return
	}

	// 获取新状态
	status, ok := data["status"].(float64)
	if !ok {
		logs.Error("无法从回调数据中获取订单状态")
		return
	}

	// 更新订单状态
	order.OrderStatus = int(status)
	if order.OrderStatus >= 3 { // 已完成或取消状态
		order.IsProcessed = 1
		order.ProcessTime = time.Now().Unix()
	}

	err = models.UpdateMeituanOrder(order)
	if err != nil {
		logs.Error("更新美团订单状态失败: %v", err)
		return
	}

	logs.Info("订单 %s 状态已更新为 %d", orderId, int(status))
}

// 保存订单到数据库
func saveOrder(config *models.Meituan, orderData map[string]interface{}) {
	// 提取订单ID
	orderId, ok := orderData["order_id"].(string)
	if !ok || orderId == "" {
		logs.Error("订单ID无效")
		return
	}

	// 提取订单数据
	orderType := 0
	if t, ok := orderData["order_type"].(float64); ok {
		orderType = int(t)
	}

	totalAmount := int64(0)
	if amount, ok := orderData["total"].(float64); ok {
		totalAmount = int64(amount * 100) // 转换为分
	}

	payment := int64(0)
	if p, ok := orderData["payment"].(float64); ok {
		payment = int64(p * 100) // 转换为分
	}

	customerName := ""
	if name, ok := orderData["customer_name"].(string); ok {
		customerName = name
	}

	customerPhone := ""
	if phone, ok := orderData["customer_phone"].(string); ok {
		customerPhone = phone
	}

	customerCount := 0
	if count, ok := orderData["customer_count"].(float64); ok {
		customerCount = int(count)
	}

	bookingTime := time.Now()
	if bookingTimeStr, ok := orderData["booking_time"].(string); ok {
		parsedTime, err := time.ParseInLocation("2006-01-02 15:04:05", bookingTimeStr, time.Local)
		if err == nil {
			bookingTime = parsedTime
		}
	}

	bookingEndTime := bookingTime.Add(2 * time.Hour) // 默认2小时
	if durationMinutes, ok := orderData["duration"].(float64); ok && durationMinutes > 0 {
		bookingEndTime = bookingTime.Add(time.Duration(durationMinutes) * time.Minute)
	}

	remark := ""
	if r, ok := orderData["remark"].(string); ok {
		remark = r
	}

	// 创建订单记录
	order := &models.MeituanOrder{
		MeituanId:      config.Id,
		StoreId:        config.StoreId,
		OrderId:        orderId,
		OrderStatus:    0, // 未处理
		OrderType:      orderType,
		TotalAmount:    totalAmount,
		Payment:        payment,
		CustomerName:   customerName,
		CustomerPhone:  customerPhone,
		CustomerCount:  customerCount,
		BookingTime:    bookingTime.Unix(),
		BookingEndTime: bookingEndTime.Unix(),
		Remark:         remark,
		IsProcessed:    0,
	}

	// 保存到数据库
	id, err := models.AddMeituanOrder(order)
	if err != nil {
		logs.Error("保存美团订单失败: %v", err)
		return
	}

	logs.Info("成功添加美团订单, ID: %d, 订单号: %s", id, orderId)
}
